package com.baizhi.service.impl;

import com.baizhi.dao.*;
import com.baizhi.entity.BzAdmin;
import com.baizhi.entity.BzAdminRole;
import com.baizhi.entity.BzRole;
import com.baizhi.entity.BzRolePermission;
import com.baizhi.service.BzRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class BzRoleServiceImpl implements BzRoleService {
    @Autowired
    private BzAdminDao adminDao;
    @Autowired
    private BzAdminRoleMapper adminRoleMapper;
    @Autowired
    private BzRoleMapper roleMapper;
    @Autowired
    private BzRolePermissionMapper rolePermissionMapper;
    @Autowired
    private BzMenuMapper menuMapper;

    /**
     * 根据用户名查询角色
     */
    @Override
    public Set<String> getRolesByUsername(String username) {
//        根据名字查询id
        BzAdmin admin = adminDao.selectOne(new QueryWrapper<BzAdmin>().eq("username", username));

//        根据管理员id查询角色id
        List<BzAdminRole> adminRoles = adminRoleMapper.selectList(new QueryWrapper<BzAdminRole>().eq("admin_id", admin.getId()));
        List<Integer> roleIds = adminRoles.stream().map(bzAdminRole -> {
            return bzAdminRole.getRoleId();
        }).collect(Collectors.toList());

//        根据角色id查询角色名字
        Set<String> roles = roleMapper.selectBatchIds(roleIds).stream().map(bzRole -> {
            return bzRole.getRoleName();
        }).collect(Collectors.toSet());
        return roles;
    }

    /**
     * 根据用户名查询权限
     */
    @Override
    public Set<String> getPermissionsByUsername(String username) {
//        根据用户名查询角色
        Set<String> rolesByUsername = getRolesByUsername(username);

//        根据角色名查询中间表 获取权限id
        List<Integer> perIds = rolePermissionMapper.selectList(
                new QueryWrapper<BzRolePermission>()
                        .in("role_name", rolesByUsername)
        ).stream().map(bzRolePermission -> {
            return bzRolePermission.getPerId();
        }).collect(Collectors.toList());

//        查询菜单表 获取权限名
        Set<String> permissions = menuMapper.selectBatchIds(perIds)
                .stream()
                .map(bzMenu -> {
                    return bzMenu.getPerms();
                }).collect(Collectors.toSet());

        return permissions;
    }
}
